#!/usr/bin/env python2

"""
Installs distutils/setuptools packages directly from zipped file.

Usage: wltr_pkg_install [source]

Source can be a path or a uri. 

"""

import sys
import os
import tarfile
import tempfile
from glob import glob
import shutil
import urllib


#from wltrcmd.setup import run_setup
import subprocess
def run_setup(project_dir, *args):
    
    os.chdir(project_dir)
    
    args = list(args)
    args.insert(0, sys.executable)
    args.insert(1, "setup.py")
    
    subprocess.call(args)
    

def download(url):
    
    target_path = os.path.join(tempfile.mkdtemp('wltrcmd'), url.split('/')[-1])
    
    webFile = urllib.urlopen(url)
    localFile = open(target_path, 'w')
    localFile.write(webFile.read())
    webFile.close()
    localFile.close()
    
    return target_path



if __name__ == '__main__':
    
    # prepare args
    args = sys.argv
    args.pop(0)
    source = args.pop(0)
    
    # download file if neccesary
    is_http = source.startswith("http://") or source.startswith("https://")
    if is_http:
        source = download(source)
    
    # extract file
    tmp = tempfile.mkdtemp(suffix='wltrcmd')
    tarfile.open(source, 'r').extractall(tmp)
    
    
    # install
    target = glob(os.path.join(tmp, "*"))[0]
    run_setup(target, 'install')

    # cleanup
    shutil.rmtree(tmp)
    if is_http: shutil.rmtree(os.path.dirname(source))


